<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--隐患排查清单类型-->
      <el-col :span="5" :xs="24">
        <div class="head-container">
          <el-input
            v-model="hiddenTypeName"
            placeholder="请输入隐患排查清单类型名称"
            clearable
            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="hiddenListTypeList"
            :props="{ label: 'hiddenListTypeName', children: '' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="hiddenListTypeRef"
            node-key="hiddenListTypeId"
            highlight-current
            :default-expand-all="true"
            @node-click="handleNodeClick"
          >
            <template class="custom-tree-node" #default="{ node, data }">
              <div
                style="
                  display: flex;
                  align-items: flex-start;
                  justify-content: space-between;
                  width: 100%;
                "
              >
                <span style="padding-left: 4px">{{ node.label }}</span>
                <span>
                  <el-tooltip content="更新" placement="top" v-if="data.isSystem !== '0'">
                    <el-button
                      link
                      type="primary"
                      icon="Edit"
                      @click="handleUpdateCheckType(data)"
                      v-hasPermi="['hidden:type:edit']"
                    ></el-button>
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top" v-if="data.isSystem !== '0'">
                    <el-button
                      link
                      type="primary"
                      icon="Delete"
                      @click="handleDeleteCheckType(data)"
                      v-hasPermi="['hidden:type:remove']"
                    ></el-button>
                  </el-tooltip>
                </span>
              </div>
            </template>
          </el-tree>
        </div>
        <div class="head-container" style="margin-top: 15px; text-align: center">
          <el-button
            width="100%"
            type="primary"
            plain
            icon="Plus"
            @click="handleAddCheckType"
            v-hasPermi="['hidden:type:add']"
          >
            新增隐患排查清单类型
          </el-button>
        </div>
      </el-col>

      <!--隐患排查清单搜索条件-->
      <el-col :span="18" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
          <el-form-item label="关键字" prop="keyValue">
            <el-input
              v-model="queryParams.keyValue"
              placeholder="请输入关键词搜索"
              clearable
              style="width: 260px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="任务类型:" label-width="88px" prop="workDayType">
            <el-select v-model="queryParams.workType" placeholder="请选择排查任务类型">
              <el-option
                v-for="dict in workTypeOptions"
                :key="dict.id"
                :label="dict.label"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="工作日类型:" label-width="100px" prop="workDayType">
            <el-select v-model="queryParams.workDayType" placeholder="请选择工作日类型">
              <el-option
                v-for="dict in workDayTypeOptions"
                :key="dict.id"
                :label="dict.label"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8 right">
          <el-col :span="24" style="display: flex; justify-content: end">
            <el-button
              width="100%"
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['hidden:check:add']"
            >
              新增
            </el-button>
          </el-col>
        </el-row>

        <!--隐患排查清单数据列表-->
        <el-table v-loading="loading" :data="hiddenCheckList">
          <el-table-column type="index" label="序号" width="55" align="center" />
          <el-table-column
            label="隐患清单名称"
            align="center"
            prop="listName"
            width="280"
          />
          <el-table-column label="排查周期" align="center" prop="checkCycleType">
            <template #default="scope">
              <span>
                {{
                  scope.row.checkCycleType
                    ? parseCheckCycle(scope.row.checkCycleType)
                    : "---"
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="排查人员/岗位" align="center" prop="checkUserType">
            <template #default="scope">
              <span>
                {{ scope.row.userPostNames ? scope.row.userPostNames : "---" }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="enableStatus">
            <template #default="scope">
              <el-switch
                v-model="scope.row.enableStatus"
                @change="handleStatusChange(scope.row)"
                active-value="1"
                inactive-value="2"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="280"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-tooltip content="修改" placement="top" v-if="scope.row.userId !== 1">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['hidden:check:edit']"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="详情" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="CircleCheck"
                  @click="handleInfo(scope.row)"
                  v-hasPermi="['hidden:check:query']"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top" v-if="scope.row.userId !== 1">
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['hidden:check:remove']"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.current"
          v-model:limit="queryParams.size"
          @pagination="getCheckListDataList"
        />
      </el-col>
    </el-row>
    <!--处理隐患排查清单的添加或修改对话框-->

    <el-dialog
      :title="title"
      v-model="open"
      width="60%"
      append-to-body
      close="closeDialog"
    >
      <el-form
        ref="hiddenCheckFormRef"
        :model="hiddenCheckForm"
        :rules="rules"
        style="margin-top: 18px"
      >
        <el-tabs
          v-model="activeTabName"
          type="card"
          class="demo-tabs"
          @tab-click="handleClick"
        >
          <el-tab-pane label="基本信息" name="1">
            <el-row :gutter="12">
              <el-col :span="12">
                <el-form-item
                  label="排查清单类型:"
                  label-width="140px"
                  prop="checkTypeId"
                >
                  <el-select v-model="hiddenCheckForm.checkTypeId" placeholder="请选择">
                    <el-option
                      v-for="dict in hiddenListTypeList"
                      :key="dict.hiddenListTypeId"
                      :label="dict.hiddenListTypeName"
                      :value="dict.hiddenListTypeId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="排查任务类型:"
                  label-width="140px"
                  prop="workDayType"
                >
                  <el-select
                    v-model="hiddenCheckForm.workType"
                    placeholder="请选择排查任务类型"
                  >
                    <el-option
                      v-for="dict in workTypeOptions"
                      :key="dict.id"
                      :label="dict.label"
                      :value="dict.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-alert type="info" show-icon :closable="false" style="margin: 6px 0">
              <p>关联风险事件清单，管控措施会直接关联风险清单的管控措施.</p>
            </el-alert>
            <el-form-item label="风险事件:" label-width="140px" prop="riskEventId">
              <el-select
                v-model="hiddenCheckForm.riskEventId"
                placeholder="请选择关联的风险事件"
                @change="selectRiskEvent"
              >
                <el-option
                  v-for="dict in riskEventOption"
                  :key="dict.riskEventId"
                  :label="dict.riskEventName"
                  :value="dict.riskEventId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="排查清单名称:" label-width="140px" prop="listName">
              <el-input
                v-model="hiddenCheckForm.listName"
                placeholder="请输入排查清单名称"
              />
            </el-form-item>
            <el-form-item label="排查人员或岗位:" label-width="140px" prop="userPostIds">
              <el-select v-model="hiddenCheckForm.checkUserType" placeholder="请选择">
                <el-option
                  v-for="dict in checkDutyTypeOption"
                  :key="dict.id"
                  :label="dict.label"
                  :value="dict.id"
                />
              </el-select>
              <el-select
                v-model="hiddenCheckForm.userPostIds"
                multiple
                clearable
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="dict in dutyOption"
                  :key="dict.id"
                  :label="dict.label"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
            <el-row :gutter="12">
              <el-col :span="12">
                <el-form-item label="排查周期:" label-width="140px" prop="checkCycleType">
                  <el-select
                    v-model="hiddenCheckForm.checkCycleType"
                    placeholder="请选择排查周期"
                  >
                    <el-option
                      v-for="dict in periodOption"
                      :key="dict.checkPeriodId"
                      :label="dict.checkPeriodName"
                      :value="dict.checkPeriodId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工作日类型:" label-width="140px" prop="workDayType">
                  <el-select
                    v-model="hiddenCheckForm.workDayType"
                    placeholder="请选择排查任务类型"
                  >
                    <el-option
                      v-for="dict in workDayTypeOptions"
                      :key="dict.id"
                      :label="dict.label"
                      :value="dict.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row
              :gutter="12"
              v-if="
                hiddenCheckForm.checkCycleType == 1 || hiddenCheckForm.checkCycleType == 2
              "
            >
              <el-col :span="12">
                <el-form-item
                  label="工作开始时间:"
                  label-width="140px"
                  prop="workStartTime"
                >
                  <el-time-select
                    v-model="hiddenCheckForm.workStartTime"
                    start="00:00:00"
                    step="00:15:00"
                    end="23:59:59"
                    format=" HH:mm:ss"
                    placeholder="工作开始时间"
                  ></el-time-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="工作结束时间:"
                  label-width="140px"
                  prop="workEndTime"
                >
                  <el-time-select
                    v-model="hiddenCheckForm.workEndTime"
                    start="00:00:00"
                    step="00:15:00"
                    end="23:59:59"
                    format=" HH:mm:ss"
                    placeholder="工作结束时间"
                  ></el-time-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="12">
              <el-col :span="12">
                <el-form-item label="排查开始时间:" label-width="140px" prop="startDate">
                  <el-date-picker
                    v-model="hiddenCheckForm.startDate"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetime"
                    placeholder="开始日期"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="排查结束时间:" label-width="140px" prop="endDate">
                  <el-date-picker
                    v-model="hiddenCheckForm.endDate"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetime"
                    placeholder="开始日期"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="排查方式" name="2">
            <el-form-item label="排查方式:" label-width="140px" prop="checkWay">
              <el-radio-group v-model="hiddenCheckForm.checkWay">
                <el-radio label="1" size="large" border>排查不做限制</el-radio>
                <el-radio label="2" size="large" border>二维码</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="清单内容" name="3">
            <el-row class="demo-radius" v-for="index of hiddenMeasureNum" :key="index">
              <el-col :span="20">
                <el-form-item label="管控措施:" label-width="140px">
                  <el-tree-select
                    v-model="
                      hiddenCheckForm.hiddenCheckMeasureList[index - 1].riskMeasureId
                    "
                    check-strictly
                    :data="measureClassFyOptions"
                    ref="measureSelect"
                    :props="{
                      value: 'id',
                      label: 'label',
                      children: 'children',
                      disabled: 'disabled',
                    }"
                    value-key="id"
                    placeholder="请选择管控措施内容"
                    filterable
                  >
                    <template class="custom-tree-node" #default="{ node, data }">
                      <div
                        style="
                          display: flex;
                          align-items: flex-start;
                          justify-content: space-between;
                          width: 100%;
                        "
                      >
                        <span style="padding-left: 4px">{{ node.label }}</span>
                      </div>
                    </template>
                  </el-tree-select>
                </el-form-item>
                <!--隐患排查内容处理 start-->
                <el-row
                  v-for="num of hiddenCheckForm.hiddenCheckMeasureList[index - 1]
                    .hiddenTroubleshootContentList.length"
                  :key="num"
                >
                  <el-form-item label="隐患排查内容:" label-width="140px">
                    <el-input
                      v-model="
                        hiddenCheckForm.hiddenCheckMeasureList[index - 1]
                          .hiddenTroubleshootContentList[num - 1].troubleshootContent
                      "
                      placeholder="请输入排查内容"
                    />
                  </el-form-item>
                  <el-button
                    v-if="
                      num ==
                      hiddenCheckForm.hiddenCheckMeasureList[index - 1]
                        .hiddenTroubleshootContentList.length
                    "
                    icon="Plus"
                    @click="addContentNum(index, num)"
                  ></el-button>
                  <el-button
                    v-if="num != 1"
                    icon="Delete"
                    @click="deleteContentNum(index, num)"
                  ></el-button>
                </el-row>
                <!--隐患排查内容处理 end-->
              </el-col>
              <el-col :span="4" style="display: flex; align-items: center">
                <el-button
                  v-if="index != 1"
                  type="primary"
                  icon="Delete"
                  @click="deleteMeasureNum(index)"
                  >删除</el-button
                >
              </el-col>
            </el-row>
            <el-row class="demo-add">
              <el-button type="primary" icon="Plus" @click="addMeasureNum"
                >新增</el-button
              >
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div v-if="showSubmit" class="dialog-footer">
          <el-button @click="nextTab('up')">上一步</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
        <div v-else class="dialog-footer">
          <el-button v-if="activeTabName == '2'" @click="nextTab('up')">上一步</el-button>
          <el-button type="primary" @click="nextTab('down')">下一步</el-button>
        </div>
      </template>
    </el-dialog>
    <!--新增或者修改隐患排查清单类型对话框-->
    <el-dialog :title="title" v-model="openType" width="680px" append-to-body>
      <el-form ref="typeFormRef" :model="typeForm" :rules="rules">
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="隐患排查清单类型名称"
              prop="hiddenListTypeName"
              label-width="180px"
            >
              <el-input
                v-model="typeForm.hiddenListTypeName"
                placeholder="请输入隐患排查清单类型名称"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitTypeForm">确 定</el-button>
          <el-button @click="cancelType">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="Troubleshooting">
import { getMeasureAndClassFyTree } from "@/api/prevent/risk/classfy";
import { listPeriod } from "@/api/prevent/hidden/period";
import { listDutyUser } from "@/api/prevent/hidden/dutyUser";
import { listDutyPost } from "@/api/prevent/hidden/dutyPost";
import { listRiskEvent, getRiskEventInfo } from "@/api/prevent/hidden/riskEvent";

import {
  listCheckListType,
  addCheckListType,
  deleteCheckListType,
  updateCheckListType,
  getCheckListType,
} from "@/api/prevent/hidden/checkListType";
import {
  listCheckList,
  addCheckList,
  deleteCheckList,
  updateCheckList,
  getCheckList,
  changeCheckListStatus,
} from "@/api/prevent/hidden/checkList";
/** 初始化数据 */
const measureOptions = ref([]); //管控措施选择项
const measureClassFyOptions = ref([]); //管控措施类型选择项
const total = ref(0);

const hiddenListTypeList = ref([]); //隐患排查清单类型列表数据
const hiddenTypeName = ref(""); //隐患排查清单类型名称
const hiddenCheckList = ref([]); //隐患排查清单数据列表
const activeTabName = ref("1"); //默认呈现第一步
/** 隐患排查清单 */
const checkDutyTypeOption = ref([
  { id: 1, label: "部门人员" },
  { id: 2, label: "岗位" },
]); //责任类型选择
const periodOption = ref([]); //隐患排查周期
const dutyUserOption = ref(); //部门人员(id,lable,child【】)
const dutyPositionOption = ref(); //岗位列表
const dutyOption = ref([]);
const riskEventOption = ref([]);
const title = ref(""); //对话框标题
const showSubmit = ref(false); //提交按钮
const hiddenMeasureNum = ref("1"); //默认有一个管控措施
const { proxy } = getCurrentInstance();
const loading = ref(true);
const open = ref(false);
const openType = ref(false);
const router = useRouter();
const checkListTypeChecked = ref(undefined);
const workTypeOptions = ref([
  {
    id: "0",
    label: "日常任务",
  },
  {
    id: "1",
    label: "主要负责人任务",
  },
  {
    id: "2",
    label: "技术负责人任务",
  },
  {
    id: "3",
    label: "操作负责人任务",
  },
]);
const workDayTypeOptions = ref([
  {
    id: "0",
    label: "每天",
  },
  {
    id: "1",
    label: "法定工作日",
  },
  {
    id: "2",
    label: "非法定工作日",
  },
]);
const data = reactive({
  typeForm: {},
  hiddenCheckForm: {
    checkWay: "1",

    hiddenCheckMeasureList: [
      {
        riskMeasureId: "",
        hiddenTroubleshootContentList: [{ troubleshootContent: "" }],
      },
    ],
  },
  rules: {
    hiddenListTypeName: [
      { required: true, message: "隐患排查清单类型名称不能为空", trigger: "blur" },
    ],
    checkTypeId: [
      { required: true, message: "隐患排查清单类型必须得选择", trigger: "blur" },
    ],
    workType: [
      { required: true, message: "隐患排查任务类型必须得选择", trigger: "blur" },
    ],
    workDayType: [{ required: true, message: "工作日类型必须得选择", trigger: "blur" }],
    workStartTime: [
      { required: true, message: "工作开始时间必须得选择", trigger: "blur" },
    ],
    workEndTime: [{ required: true, message: "工作结束时间必须得选择", trigger: "blur" }],
    listName: [
      { required: true, message: "隐患排查清单名称必须填写！", trigger: "blur" },
      {
        min: 3,
        max: 50,
        message: "隐患排查清单名称必须介于 3 和 50 之间",
        trigger: "blur",
      },
    ],
    userPostIds: [
      { required: true, message: "隐患排查责任人必须选择！", trigger: "blur" },
    ],
    checkCycleType: [
      { required: true, message: "隐患排查周期必须选择！", trigger: "blur" },
    ],

    startDate: [
      { required: true, message: "隐患排查开始结束时间必须选择！", trigger: "blur" },
    ],
    endDate: [
      { required: true, message: "隐患排查开始结束时间必须选择！", trigger: "blur" },
    ],
    checkWay: [{ required: true, message: "隐患排查方式必须选择！", trigger: "blur" }],
    troubleshootContent: [
      { required: true, message: "隐患排查内容必须填写！", trigger: "blur" },
      {
        min: 3,
        max: 50,
        message: "隐患排查内容必须介于 5 和 150 之间",
        trigger: "blur",
      },
    ],
  },
  queryParams: {
    current: 1,
    size: 10,
  },
});
const { typeForm, hiddenCheckForm, rules, queryParams } = toRefs(data);
/** 根据名称筛选管控措施类型 */
watch(hiddenTypeName, (val) => {
  proxy.$refs["hiddenListTypeRef"].filter(val);
});

/** 处理排查周期数据 */
function parseCheckCycle(checkCycleType) {
  if (periodOption.value.length < 1) return "---";
  var itemTarget = periodOption.value.filter((item) => {
    return item.checkPeriodId == checkCycleType;
  });

  return itemTarget[0].checkPeriodName;
}

/** ------------init------------- */
/** 获取管控措施类型及内容列表数据 */
function getRiskMeasureClassfyList() {
  getMeasureAndClassFyTree().then((response) => {
    measureClassFyOptions.value = response.data;
  });
}

/** 获取隐患排查周期列表数据 */
async function getPeriodList() {
  listPeriod().then((response) => {
    periodOption.value = response.data;
  });
}

/** 获取排查责任人数据列表 */
async function getCheckUserList() {
  listDutyUser().then((response) => {
    dutyUserOption.value = response.data;
  });
}

/** 获取排查责任岗位数据列表 */
async function getCheckPostList() {
  listDutyPost().then((response) => {
    dutyPositionOption.value = response.data;
  });
}

/** 获取风险事件清单数据列表 */
async function getRiskEventList() {
  listRiskEvent().then((response) => {
    riskEventOption.value = response.data;
  });
}

/** 监听排查类型 */
watch(
  () => hiddenCheckForm.value.checkUserType,
  (newValue, oldValue) => {
    console.log("监听排查类型");
    dutyOption.value = [];
    if (hiddenCheckForm.value.listId == undefined || oldValue != undefined) {
      hiddenCheckForm.value.userPostIds = [];
    }

    if (newValue == "1") {
      dutyOption.value = dutyUserOption.value;
    } else if (newValue == "2") {
      dutyOption.value = dutyPositionOption.value;
    }
  }
);
/**---------------隐患排查清单类型处理 */
/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.hiddenListTypeName.indexOf(value) !== -1;
};
/** 节点单击事件 */
function handleNodeClick(data, node) {
  console.log(data);
  checkListTypeChecked.value = data.hiddenListTypeId;
  queryParams.value.checkTypeId = data.hiddenListTypeId;
  getCheckListDataList();
}
/** 重置隐患排查清单类型表单 */
function resetTypeForm() {
  typeForm.value = {
    hiddenListTypeName: "",
  };
  proxy.resetForm("typeFormRef");
}
/** 获取隐患排查清单类型列表 */
function getHiddenTypeList() {
  loading.value = true;
  listCheckListType().then((response) => {
    hiddenListTypeList.value = response.data;
    loading.value = false;
  });
}
/** 添加隐患排查清单类型 */
function handleAddCheckType() {
  resetTypeForm();
  title.value = "添加隐患排查清单类型";
  openType.value = true;
}
/** 删除隐患排查清单类型 */
function handleDeleteCheckType(row) {
  proxy.$modal
    .confirm('是否确认删除名称为"' + row.hiddenListTypeName + '"的数据项?')
    .then(function () {
      return deleteCheckListType(row.hiddenListTypeId);
    })
    .then(() => {
      getHiddenTypeList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 修改隐患排查清单类型 */
async function handleUpdateCheckType(row) {
  resetTypeForm();
  getCheckListType(row.hiddenListTypeId).then((response) => {
    typeForm.value = response.data;
    openType.value = true;
    title.value = "修改隐患排查清单类型";
  });
}

/** 提交隐患排查清单类型数据 */
function submitTypeForm() {
  proxy.$refs["typeFormRef"].validate((valid) => {
    if (valid) {
      if (typeForm.value.hiddenListTypeId != undefined) {
        updateCheckListType(typeForm.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          openType.value = false;
          getHiddenTypeList();
        });
      } else {
        addCheckListType(typeForm.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          openType.value = false;
          getHiddenTypeList();
        });
      }
    }
  });
}

/** 取消隐患排查清单类型对话框 */
function cancelType() {
  resetTypeForm();
  openType.value = false;
}

/**---------------------隐患排查清单处理------------------------- */

/** 获取隐患排查清单列表 */
function getCheckListDataList() {
  loading.value = true;
  listCheckList(queryParams.value).then((response) => {
    loading.value = false;
    hiddenCheckList.value = response.data.dataList;
    total.value = response.data.totalNum;
  });
}

/** 处理TAB切换 */
const handleClick = (tab, event) => {
  if (tab.props.name == "3") {
    showSubmit.value = true;
  } else {
    showSubmit.value = false;
  }
};

/** 搜索按钮操作 */
function handleQuery() {
  getCheckListDataList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    current: 1,
    size: 10,
    checkTypeId: checkListTypeChecked.value,
  };
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 处理添加 */
function handleAdd() {
  open.value = true;
  title.value = "新增隐患排查清单";
  reset();
}
/** 删除按钮 */
function handleDelete(row) {
  proxy.$modal
    .confirm("是否确认删除" + row.listName + "的数据项？")
    .then(function () {
      return deleteCheckList(row.listId);
    })
    .then(() => {
      getCheckListDataList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 更新按钮 */
function handleUpdate(row) {
  reset();
  getCheckList(row.listId).then((response) => {
    //console.log("更新接口返回数据", response.data);

    const arr = [];
    response.data.userPostIds.split(",").forEach((item) => {
      arr.push(parseInt(item));
    });
    response.data.userPostIds = arr;
    hiddenCheckForm.value = response.data;

    console.log("更新的数据", hiddenCheckForm.value);
    hiddenMeasureNum.value = response.data.hiddenCheckMeasureList.length;

    open.value = true;
    title.value = "更新隐患排查清单";
  });
}
/** 详情按钮 */
function handleInfo(row) {
  router.push("/hidden/checkList/info/" + row.listId);
}

/** 重置表单 */
function reset() {
  hiddenCheckForm.value = {
    checkWay: "1",
    checkTypeId: checkListTypeChecked.value,
    hiddenCheckMeasureList: [
      {
        riskMeasureId: "",
        hiddenTroubleshootContentList: [{ troubleshootContent: "" }],
      },
    ],
  };
  proxy.resetForm("hiddenCheckFormRef");
  hiddenMeasureNum.value = 1;
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 对话框切换下一步 */
function nextTab(flag) {
  if (activeTabName.value == "1") {
    //proxy.$refs["eventRef"].validate(valid => {});
    setTimeout(() => {
      activeTabName.value = "2";
    }, 500);
  } else if (activeTabName.value == "2") {
    if (flag == "up") {
      activeTabName.value = "1";
    } else {
      //proxy.$refs["methodRef"].validate(valid => {});
      setTimeout(() => {
        activeTabName.value = "3";
        showSubmit.value = true;
      }, 500);
    }
  } else {
    showSubmit.value = false;
    activeTabName.value = "2";
  }
}

/** 提交 */
function submitForm() {
  proxy.$refs["hiddenCheckFormRef"].validate((valid) => {
    if (valid) {
      hiddenCheckForm.value.userPostIds = hiddenCheckForm.value.userPostIds + "";
      console.log("提交的数据", hiddenCheckForm.value);
      if (hiddenCheckForm.value.listId != undefined) {
        updateCheckList(hiddenCheckForm.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getCheckListDataList();
        });
      } else {
        console.log("进入表单提交", hiddenCheckForm.value);
        addCheckList(hiddenCheckForm.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getCheckListDataList();
        });
      }
    }
  });
}

/** 关联风险事件 */
function selectRiskEvent(val) {
  console.log("关联的风险清单", val);
  hiddenMeasureNum.value = 1;
  resetMeasureData();
  getRiskEventInfo(val).then((response) => {
    if (response.data.riskEventMeasureList.length > 0) {
      response.data.riskEventMeasureList.forEach((item, index) => {
        if (index > 0) {
          addMeasureNum();
        }

        hiddenCheckForm.value.hiddenCheckMeasureList[index].riskMeasureId =
          item.riskMeasureId + "";
      });
    }
  });
}

/** 清空管控数据 */
function resetMeasureData() {
  hiddenCheckForm.value.hiddenCheckMeasureList = [
    {
      riskMeasureId: "",
      hiddenTroubleshootContentList: [{ troubleshootContent: "" }],
    },
  ];
}

/** 添加风险的管控措施 */
function addMeasureNum() {
  hiddenCheckForm.value.hiddenCheckMeasureList.push({
    riskMeasureId: "",
    hiddenTroubleshootContentList: [{ troubleshootContent: "" }],
  });
  hiddenMeasureNum.value++;
}

/** 删除当前的管控措施 */
function deleteMeasureNum(index) {
  if (hiddenMeasureNum.value > 1) {
    hiddenCheckForm.value.hiddenCheckMeasureList.splice(index - 1, 1);
    hiddenMeasureNum.value--;
  }
}

/** 添加隐患排查内容 */
function addContentNum(index, num) {
  hiddenCheckForm.value.hiddenCheckMeasureList[
    index - 1
  ].hiddenTroubleshootContentList.push({ troubleshootContent: "" });
}
/** 删除某个管控措施下面的隐患排查内容 */
function deleteContentNum(index, num) {
  hiddenCheckForm.value.hiddenCheckMeasureList[
    index - 1
  ].hiddenTroubleshootContentList.splice(num - 1, 1);
}

/** 清单状态修改  */
function handleStatusChange(row) {
  let text = row.status === "1" ? "启用" : "停用";
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.listName + '"任务吗?')
    .then(function () {
      return changeCheckListStatus({
        listId: row.listId,
        enableStatus: row.enableStatus,
      });
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.status = row.status === "1" ? "2" : "1";
    });
}

/*** 初始化调用 */
getPeriodList(); //获取隐患排查周期
getRiskMeasureClassfyList();
getHiddenTypeList();
getCheckListDataList(); //获取隐患排查清单列表

getCheckUserList(); //获取排查人员数据列表
getCheckPostList(); //获取排查岗位数据列表
getRiskEventList(); //获取风险清单
</script>
<style>
/* .is-active {
  background-color: #1989fa;
  color: #ffffff !important;
} */
.demo-radius {
  width: 90%;
  border: 1px solid var(--el-border-color);
  border-radius: 5px;
  margin: 20px;
  padding: 20px;
}
.demo-add {
  width: 90%;
  margin: 20px;

  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}
:deep(.el-select .el-select--default) {
  width: 100% !important;
}
</style>
